package com.red.star.wechat.work.site.banner;


import com.alibaba.fastjson.JSON;
import com.red.star.wechat.data.entity.Banner;
import com.red.star.wechat.data.entity.Mall;
import com.red.star.wechat.data.entity.MallBanner;
import com.red.star.wechat.data.entity.SysParam;
import com.red.star.wechat.data.entity.vo.MallBannerDataVo;
import com.red.star.wechat.data.entity.vo.SortBanner;
import com.red.star.wechat.data.utils.CheckUtil;
import com.red.star.wechat.data.utils.FileUtil;
import com.red.star.wechat.work.constant.AdminSessionHolder;
import com.red.star.wechat.work.entity.Admin;
import com.red.star.wechat.work.entity.TableContainer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/work")
public class BannerController {

    @Resource
    private BannerService bannerService;


    @RequestMapping("/bannerTemplateTest")
    public ModelAndView receptionGroup() {
        Admin admin = AdminSessionHolder.get();
        ModelAndView modelAndView = new ModelAndView();

        modelAndView.setViewName("bannerTemplateTest");
        try {
            String token = FileUtil.fetchToken(SysParam.MACALLINE_FILE_EMPLOYEE_ID);
            if (CheckUtil.isEmpty(token)) {
                token = "";
            }
            modelAndView.addObject("token", token);
        } catch (Exception e) {
            System.out.println("获取token异常");
        }

        modelAndView.addObject("fileUploadUrl", SysParam.MACALLINE_FILE_UPLOAD_URL);
        return modelAndView;
    }

    //前端取Banner逻辑，根据mall_code，首先查出集团设置的占位banner，然后剩下的位置按自己的排序填充
    @RequestMapping("/getBanner")
    public String getBanner(String mallCode) {
        TreeMap<Integer, Banner> bannerMap = new TreeMap<Integer, Banner>();
        List<Banner> bannerList = new ArrayList<>();
        List<MallBanner> groupList = bannerService.findBannerOrderByMallCode(mallCode);  //集团占位BannerList
        for (MallBanner mallBanner : groupList) {
            Integer order = mallBanner.getBannerOrder();                  //集团占位Banner的位置（1-6）
            Banner groupBanner = bannerService.findBannerByBannerId(mallBanner.getBannerId());
            bannerMap.put(order, groupBanner);
        }
        List<Banner> mallList = bannerService.findSortBannerByMallCode(mallCode);     //商场所有排序的BannerList
        Integer bannerSize = groupList.size() + mallList.size();
        if (bannerSize > 6) {
            bannerSize = 6;
        }
        int j = 1;
        for (int i = 1; i <= bannerSize; i++) {
            if (CheckUtil.isEmpty(bannerMap.get(i))) {
                for (Banner banner : mallList) {
                    if (j == banner.getSort()) {
                        bannerMap.put(i, banner);
                        j++;
                        break;
                    }
                }
            }
        }
        for (int k = 1; k <= bannerMap.size(); k++) {
            bannerList.add(bannerMap.get(k));
        }

//        return "";
        return CheckUtil.isEmpty(JSON.toJSONString(bannerList)) ? "NoBanner" : JSON.toJSONString(bannerList);
    }


    public static void main(String[] args) {
        TreeMap<Integer, String> map = new TreeMap<Integer, String>();
        map.put(3, "3");
        map.put(4, "4");
        map.put(1, "1");
        System.out.println(map);
        for (Map.Entry entry : map.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    }

    /*
     * banner顺序管理页面
     */
    @RequestMapping("/orderManagement")
    public ModelAndView orderManagemant() {
        ModelAndView modelAndView = new ModelAndView();
        Admin admin = AdminSessionHolder.get();
        List<MallBannerDataVo> bannerList = bannerService.selectWorkableBanner(admin.getMallCode());
        modelAndView.addObject("bannerList", bannerList);
        modelAndView.setViewName("orderManagement");
        return modelAndView;
    }


    /*
     * banner上架
     */
    @RequestMapping("/putawayBanner")
    public ResponseEntity<?> putawayBanner(SortBanner sortBanner) {
        try {
            if (!sortBanner.getSortBanner().isEmpty()) {
                bannerService.putawayBannerStatus(sortBanner.getSortBanner());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }

    /*
     * banner下架
     */
    @RequestMapping("/removeBanner")
    public ResponseEntity<?> removeBanner(String bannerId) {
        try {
        	if (!CheckUtil.isEmpty(bannerId)) {
        		bannerService.removeBannerStatus(bannerId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<>(true, HttpStatus.OK);
    }

    /*
     * banner顺序管理
     */
    @RequestMapping("/onlineBannerList")
    public ResponseEntity<?> bannerOrder() {
        Admin admin = AdminSessionHolder.get();
        String mallCode = admin.getMallCode();
        List<MallBannerDataVo> list = bannerService.selectValidBanner(mallCode);
        return new ResponseEntity<>(list, HttpStatus.OK);
    }
//

    /*
     * banner数据统计页面
     */
    @RequestMapping("/groupBannerData")
    public ModelAndView groupDataStatistics() {
        Admin admin = AdminSessionHolder.get();
        String mallCode = admin.getMallCode();
        List<Mall> mallList = bannerService.selectAllMall(mallCode);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("bannerData");
        modelAndView.addObject("mallList",mallList);
        return modelAndView;
    }


    /*
     * banner数据统计
     */
    @RequestMapping("/querBannerData")
    public ResponseEntity<?> queryGroupDataStatistics(MallBannerDataVo mallBannerDataVo) throws ParseException {
        TableContainer tableContainer = bannerService.queryBannerData(mallBannerDataVo);
        return new ResponseEntity<>(tableContainer, HttpStatus.OK);

    }

    @RequestMapping("/exploreBannerData")
    public ResponseEntity<?> exploreReceptionData(String bannerId, String bannerName, String status, String mallCode, String startTime, String endTime) throws UnsupportedEncodingException, ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = "";
        if (CheckUtil.isEmpty(mallCode)) {
            fn = "集团banner数据统计" + sdf.format(new Date()).toString() + ".csv";
        } else {
            fn = "商场banner数据统计" + sdf.format(new Date()).toString() + ".csv";
        }
        // 读取字符编码
        String utf = "UTF-8";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
        Date eTime = null;
        Date stdTime =null;
        if (!CheckUtil.isEmpty(startTime)) {
            stdTime = new SimpleDateFormat("yyyy-MM-dd").parse(startTime);
        }
        if (!CheckUtil.isEmpty(endTime)) {
            eTime = new SimpleDateFormat("yyyy-MM-dd").parse(endTime);
            //结束时间加一天
            if (!CheckUtil.isEmpty(eTime)){
                Calendar calendar  = new  GregorianCalendar();
                calendar.setTime(eTime);
                calendar.add(calendar.DATE,1);
                eTime=calendar.getTime();
            }
        }
        byte[] body = bannerService.exploreBannerData(bannerId, bannerName, status, mallCode, stdTime, eTime);
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, httpHeaders, HttpStatus.OK);
        return entity;
    }

}
